package individual.mamingchao.scratch_story.service.impl;

import individual.mamingchao.scratch_story.dao.MaterialMapper;
import individual.mamingchao.scratch_story.service.MaterialService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mamingchao on 2020/12/25.
 */
@Service
public class MaterialServiceImpl implements MaterialService{

    @Autowired
    private MaterialMapper materialMapper;

    /**
     * 保存新增材料
     *
     * @param material
     * @return
     */
    @Override
    public boolean saveMaterial(MaterialDto material) {
        int num = this.materialMapper.insertSelective(this.convertMaterialDto2Material(material, true));
        return num == 1;
    }

    /**
     * 删除材料信息
     *
     * @param id
     * @return 返回成功与否
     */
    @Override
    public boolean delMaterial(short id) {

        int num = this.materialMapper.deleteByPrimaryKey(id);

        return num == 1;
    }

    /**
     * 更新 材料信息
     *
     * @param material
     * @return 返回更新后的 材料信息
     */
    @Override
    public MaterialDto updMaterial(MaterialDto material) {
        Assert.isNull(material.getId(),"更新材料，缺少主键字段");
        return null;
    }

    /**
     * 通过 章节编码获取该章节 所有可用的 材料
     *
     * @param chapterCode
     * @return
     */
    @Override
    public List<MaterialDto> queryByChapterCode(String chapterCode) {
        List<MaterialDto> result = new ArrayList<>();

        List<Material> materials = this.materialMapper.queryByChapterCode(chapterCode);
        materials.stream().forEach(item -> {
            result.add(this.convertMaterial2MaterialDto(item, true));
        });
        return result;
    }


    /**
     * 将 MaterialDto 转化成 Material
     * @param dto
     * @return
     */
    private Material convertMaterialDto2Material(MaterialDto dto, boolean gcParam) {
        Material material = new Material();
        BeanUtils.copyProperties(dto,material);

        if (gcParam)
            dto = null;// help GC
        return material;
    }


    /**
     * 将 Material 转化成 MaterialDto
     * @param material
     * @return
     */
    private MaterialDto convertMaterial2MaterialDto(Material material, boolean gcParam) {
        MaterialDto MaterialDto= new MaterialDto();
        BeanUtils.copyProperties(material,MaterialDto);
        if (gcParam)
            material = null; // help GC
        return MaterialDto;
    }
}
